# _*_ coding:utf-8 _*_
# @File  : application.py
# @Time  : 2021-10-26  09:57
# @Author: zizle

from fastapi import APIRouter, Path, Body
from db import FAConnection
from db import utils as dbutils
from status import r_status

admin_application_api = APIRouter()


@admin_application_api.get('/', summary='查询所有申请记录')
async def admin_user_application():
    state_explain = {0: '待处理', 1: '通过未发号', 2: '通过已发号', 3: '拒绝'}

    db = FAConnection(conn_name='admin查询申请')
    sql = 'SELECT id,create_time,company,username,phone,state,client_code,introducer,description ' \
          'FROM user_application order by create_time DESC;'
    records = db.query(sql)
    for item in records:
        item['create_time'] = item['create_time'].strftime('%Y-%m-%d %H:%M:%S')
        item['state_explain'] = state_explain.get(item['state'])

    return {'code': r_status.SUCCESS, 'message': '查询成功!', 'data': records}


# 处理一个申请记录状态
@admin_application_api.put('/{apply_id}/', summary='修改审核状态')
async def user_application_handler(apply_id: int = Path(..., ge=1), body_item: dict = Body(...)):
    # 修改状态 0: '待处理'(默认), 1: '通过未发号', 2: '通过已发号', 3: '拒绝'
    # 检测数据，接受state与description字段数据
    accept_json = dbutils.exclude_columns(body_item, ['state', 'description'])
    middle_sql = dbutils.create_sql(accept_json)
    accept_json['id'] = apply_id

    db = FAConnection(conn_name='修改申请状态')
    sql = 'UPDATE user_application SET ' + middle_sql + ' WHERE id=%(id)s LIMIT 1;'
    _, s = db.execute(sql, param=accept_json)

    return {'code': r_status.SUCCESS, 'message': '修改状态成功!'}
